import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/token-manage'
import getPageTitle from '@/utils/get-page-title'

// 进度条配置
NProgress.configure({ easing: 'ease', speed: 500, trickleSpeed: 200, showSpinner: false })

// 路由白名单
const whiteList = ['/', '/login', '/registe']

// 权限路由跳转的隐藏路由 - 未通过菜单配置(二级子页面)
const permissionRoutesWhiteList = []

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const hasToken = getToken()
    if (hasToken) {
        /* has token*/
        if (to.path === '/login' || to.path === '/') {
            next({ path: '/dashboard' })
            NProgress.done()
        } else if (permissionRoutesWhiteList.indexOf(to.path) !== -1) {
            // 隐藏的路由 - 未通过菜单配置(二级子页面)
            next({ ...to, replace: true })
        } else {
            const authRoutes = store.getters.authRoutes
            // 判断权限路由
            if (authRoutes && authRoutes.length > 0) {
                next()
            } else {
                try {
                    // 刷新 - 初始化路由
                    await store.dispatch('permission/initAuthRoutes')
                    next({ ...to, replace: true })
                } catch (error) {
                    setTimeout(() => {
                        store.dispatch('user/resetToken')
                        NProgress.done()
                    }, 1500)
                }
            }
        }
    } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next({ path: '/login' })
            NProgress.done()
        }
    }
})

router.afterEach((to, from) => {
    document.title = getPageTitle(to.meta.title)
    NProgress.done()
})
